﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using Com.ContentRendering.Api.RenderEngine;

namespace Com.ContentRendering.Api.RenderEngineComponentTest.Helper
{
    internal class InputDataHelper : InputDataInterface
    {
        XmlNode _xmlNode;

        internal InputDataHelper(XmlNode xmlNode)
        {
            this._xmlNode = xmlNode;
        }

        public IEnumerator<InputDataInterface> FetchParentData(int level)
        {
            XmlNode xmlNode = this._xmlNode;

            // find the parent node
            for (int index = 0; index < level; index++)
            {
                xmlNode = xmlNode.ParentNode;
            }

            List<InputDataInterface> inputDataHelpers = new List<InputDataInterface>();

            inputDataHelpers.Add(new InputDataHelper(xmlNode));

            return inputDataHelpers.GetEnumerator();
        }

        public IEnumerator<InputDataInterface> FetchChildData(string name)
        {
            return this.FetchInputDataHelperEnumerator(this._xmlNode, name);
        }

        public IEnumerator<InputDataInterface> FetchRootData(string name)
        {
            XmlNode xmlNode = this._xmlNode;

            // find the root node
            while (xmlNode.Name != "document")
            {
                xmlNode = xmlNode.ParentNode;
            }

            return this.FetchInputDataHelperEnumerator(xmlNode, name);
        }

        public string Value
        {
            get { return this._xmlNode.InnerText; }
        }

        private IEnumerator<InputDataInterface> FetchInputDataHelperEnumerator(
            XmlNode xmlNode,
            string name)
        {
            List<InputDataInterface> inputDataHelpers = new List<InputDataInterface>();

            foreach (XmlNode childXmlNode in xmlNode.ChildNodes)
            {
                // compare the name ... if its the same then create a child
                if (childXmlNode.Name != name)
                {
                    continue;
                }

                inputDataHelpers.Add(new InputDataHelper(childXmlNode));
            }

            return inputDataHelpers.GetEnumerator();
        }
    }
}
